<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>

    <style>
        #video {
            display: block;
            margin: 1em auto;
            width: 100vh;
            height: 180px;
        }

        video {
            background: rgba(255, 255, 255, 0.5);
        }

        .grayscale {
            filter: grayscale(1);
        }

        .sepia {
            filter: sepia(1);
        }

        .blur {
            filter: blur(3px);
        }
    </style>
    <br>
    <br>
    <button type="button" id="btn" style="outline: none;border: 1px solid #ddd;border-radius: 4px;height: 30px;line-height:30px;width:100px;">开始扫描</button>
    <br>
    <br>
    <input type="button" id="capture" value="截图" />
    <br>
    <canvas id="canvas" width=300></canvas>
    <video id="video" autoplay></video>
    <input type="file">
    <select name="video" id="select"></select>
    <button type='button' onclick='shoot()'>下载</button>
    <script src="https://bluelotos.gitee.io/lib/vconsole/dist/vconsole.min.js"></script>
    <script>
        var vConsole = new VConsole();
        const video = document.getElementById('video');
        const button = document.getElementById('btn');
        const select = document.getElementById('select');
        let currentStream;
        var count = 0;
        video.onclick = () => {
            count++;
            switch (count) {
                case 1:
                    video.className = 'grayscale';
                    break;
                case 2:
                    video.className = 'sepia';
                    break;
                case 3:
                    video.className = 'blur';
                    break;
                case 4:
                    video.className = '';
                    count = 0;
                    break;
            }
        }

        function stopMediaTracks(stream) {
            stream.getTracks().forEach(track => {
                track.stop();
            });
        }

        function gotDevices(mediaDevices) {
            select.innerHTML = '';
            select.appendChild(document.createElement('option'));
            let count = 1;
            mediaDevices.forEach(mediaDevice => {
                console.log(mediaDevice)
                if (mediaDevice.kind === 'videoinput') {
                    const option = document.createElement('option');
                    option.value = mediaDevice.deviceId;
                    const label = mediaDevice.label || '摄像头' + (count++);
                    const textNode = document.createTextNode(label);
                    option.appendChild(textNode);
                    select.appendChild(option);
                    select.value = mediaDevice.deviceId;
                }
            });

        }

        button.addEventListener('click', event => {
            if (typeof currentStream !== 'undefined') {
                stopMediaTracks(currentStream);
            }
            const videoConstraints = {};
            if (select.value === '') {
                videoConstraints.facingMode = 'environment';
            } else {
                videoConstraints.deviceId = {
                    exact: select.value
                };
            }
            const constraints = {
                video: videoConstraints,
                audio: false
            };
            navigator.mediaDevices
                .getUserMedia(constraints)
                .then(stream => {
                    currentStream = stream;
                    video.srcObject = stream;
                    video.onloadedmetadata = function (e) {
                        video.play();
                        bindCapture();
                    };
                    return navigator.mediaDevices.enumerateDevices();
                })
                .then(gotDevices)
                .catch(error => {
                    console.error(error);
                });
        });

        navigator.mediaDevices.enumerateDevices().then(gotDevices);

        function getScan() {
            if (typeof currentStream !== 'undefined') {
                stopMediaTracks(currentStream);
            }
            const myConstraints = {
                audio: false,
                video: {
                    facingMode: "environment"
                }
                /* video: {
                    facingMode: {
                        exact: "environment"
                    },
                    height: 300,
                    frameRate: {
                        ideal: 10,
                        max: 15
                    }
                } */
            }
            navigator.mediaDevices.getUserMedia(myConstraints)
                .then(function (mediaStream) {
                    // 旧的浏览器可能没有srcObject
                    if ("srcObject" in video) {
                        video.srcObject = mediaStream;
                    } else {
                        // 防止再新的浏览器里使用它，应为它已经不再支持了
                        // createObjectURL是个非常有用的API，诸位可以多研究研究
                        video.src = window.URL.createObjectURL(mediaStream);
                    }
                    video.onloadedmetadata = function (e) {
                        video.play();
                        bindCapture();
                    };
                })
                .catch(function (err) {
                    console.log(err.name + ": " + err.message);
                }); // 总是在最后检查错误
        }

        function bindCapture() {
            var videoWidth = 300,
                videoHeight = 300 / video.videoWidth * video.videoHeight;
            if (videoWidth && videoHeight) {
                var canvas = document.getElementById('canvas');
                canvas.width = videoWidth;
                canvas.height = videoHeight;
                document.getElementById('capture').addEventListener(
                    'click',
                    function () {
                        canvas.getContext('2d').drawImage(
                            video, 0, 0, videoWidth, videoHeight
                        );
                    },
                    false
                );
            } else {
                setTimeout(bindCapture, 200);
            }
        }

        function shoot() {
            var canvas = document.createElement('canvas');
            canvas.width = 640;
            canvas.height = 480;
            var ctx = canvas.getContext('2d');
            ctx.drawImage(video, 0, 0);
            canvas.toBlob((myblob) => {
                download(myblob);
            });
        }

        function download(blob) {
            var a = document.createElement('a');
            a.href = URL.createObjectURL(blob);
            a.download = Math.random().toString(36).substr(2, 14);
            a.click();
        }
    </script>
</body>

</html>